package com.amadeus.personal_demo;

import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import android_serialport_api.SerialPort;

import static android.content.ContentValues.TAG;

public class QRReadThread extends Thread {
    boolean flag = true;
    private static final String PORT = "/dev/ttyS4" ;
    private static int MAXBUFLEN = 1024;
    private int recvIndex = 0;
    private int maxLen = 0;
    private int reacvtimer;

    SerialPort mSerialPort;
    private InputStream mInputStream;
    private Byte mRecvBuf[] = new Byte[MAXBUFLEN];

    QRReadThread(){
        try{
            File com = new File(PORT);
            Log.e(TAG,"mSerialPort = new SerialPort(com,115200,0);");
            System.out.println("mSerialPort = new SerialPort(com,115200,0);");
            mSerialPort = new SerialPort(com,9600,0);
            mInputStream = mSerialPort.getInputStream();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void Destroy(){
        flag = false;
        this.interrupt();
        mSerialPort = null;
        mInputStream = null;
    }

    @Override
    public void run() {
        super.run();
        while(flag){
            if (mInputStream == null){
                return;
            }
            try {
                if(mInputStream.available()>0){
                    byte[] buffer = new byte[1024];
                    int size;
                    size = mInputStream.read(buffer);
                    if (size > 0) {
                        //mDioFunc.debugmsg(pHexToString(buffer,size));
                        recvIndex = 0;
                        RecvData(buffer,size);
                    }
                    buffer = null;

                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                Thread.currentThread().sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private void RecvData(byte[] buf,int size){
        int i;String tmp;
        for(i=0;i<size;i++){
            if(buf[i]==0xd){
                byte[] m = new byte[recvIndex-1];
                for(int j=0;j<recvIndex-1;j++) {
                    m[j] = mRecvBuf[j+1];
                }
                tmp = new String(m);
                MainActivity.getInstance().QRPro(mRecvBuf[0],tmp);
                Log.d(TAG, "RecvData: "+tmp);
                recvIndex = 0;
            }
            mRecvBuf[recvIndex]=buf[i];
            recvIndex++;
        }
    }
}
